package com.signway.harmony_demo;

import com.signway.harmony_demo.slice.MainAbilitySlice;
import com.signway.harmony_demo.slice.MathDrawRemSlice;
import com.signway.harmony_demo.slice.MathGameAbilitySlice;
import com.signway.harmony_demo.utils.CommonData;
import com.signway.harmony_demo.utils.LogUtil;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.bundle.IBundleManager;

import static ohos.security.SystemPermission.DISTRIBUTED_DATASYNC;

public class MainAbility extends Ability {
    public static final String TAG = CommonData.TAG + MainAbility.class.getSimpleName();
    public static final int PERMISSION_CODE = 10000000;

    @Override
    public void onStart(Intent intent) {
        LogUtil.info(TAG, "onStart");
        super.onStart(intent);
        super.setMainRoute(MainAbilitySlice.class.getName());
        addActionRoute(CommonData.DRAW_PAGE, MathDrawRemSlice.class.getName());
        addActionRoute(CommonData.MATH_PAGE, MathGameAbilitySlice.class.getName());
        grantPermission();
    }

    void grantPermission() {
        if (verifySelfPermission(DISTRIBUTED_DATASYNC) != IBundleManager.PERMISSION_GRANTED) {
            if (canRequestPermission(DISTRIBUTED_DATASYNC)) {
                requestPermissionsFromUser(new String[] {DISTRIBUTED_DATASYNC}, PERMISSION_CODE);
            }
        }
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsFromUserResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_CODE: {
                if (grantResults.length > 0 && grantResults[0] == IBundleManager.PERMISSION_GRANTED) {
                    LogUtil.info(TAG, "权限被授予");
                    LogUtil.info(TAG, "启动服务");
                    Intent intent1 = new Intent();
                    Operation operation = new Intent.OperationBuilder()
                            .withBundleName(getBundleName())
                            .withAbilityName("MathGameServiceAbility")
                            .build();
                    intent1.setOperation(operation);
                    startAbility(intent1);
                } else {
                    LogUtil.info(TAG, "权限被拒接");
                    grantPermission();
                }
            } break;
        }
    }
}
